package com.teaching.Controller;

import com.teaching.Common.R;
import com.teaching.Entity.Teacher;
import com.teaching.Service.TeacherService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;

@RestController
@Slf4j
@RequestMapping("/teacher")
public class TeacherController {
    @Value("${teaching.path}")
    private String path;

    @Autowired
    private TeacherService teacherService;

    @PostMapping("/list")
    private R<ArrayList<HashMap>> list(@RequestBody HashMap<String, Object> data) {
        List<Teacher> list = teacherService.ListSize(data);
        ArrayList<HashMap> teachers = new ArrayList<>();
        for (Teacher teacher : list) {
            HashMap<String, Object> HashMap = new HashMap<>();
            HashMap.put("id", teacher.getId());
            HashMap.put("teacherName", teacher.getTeacherName());
            HashMap.put("teacherCover", teacher.getTeacherCover());
            HashMap.put("teacherClass", teacher.getTeacherClass());
            HashMap.put("funsNumber", teacher.getFunsNumber());
            teachers.add(HashMap);
        }
        return R.success(teachers);
    }

    @PostMapping("/uploadphoto")
    public R<String> uploadPhoto(Long id, @RequestPart("file") MultipartFile file) {
        //1234.png
        String originalFilename = file.getOriginalFilename();
        //.png
        String substring = originalFilename.substring(originalFilename.lastIndexOf("."));
        //images\\4312.png
        String s = "images\\photo\\" + UUID.randomUUID() + substring;
        //D:\\teaching\\images\\photo\\
        File dir = new File(path + "images\\photo\\");
        if (!dir.exists()) {
            dir.mkdirs();
        }
        Teacher byId = teacherService.getById(id);
        //D:\\teaching\\images\\photo\\00.png
        File file1 = new File(path + byId.getTeacherPhoto());
        if (file1.exists()) {
            file1.delete();
        }
        byId.setTeacherPhoto(s);
        teacherService.updateById(byId);
        try {
            file.transferTo(new File(path + s));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return R.success(s);
    }

    @PostMapping("/byid")
    public R<Teacher> byId(Integer id) {
        log.info(String.valueOf(id));
        Teacher byId = teacherService.getById(id);
        return R.success(byId);
    }
    @GetMapping("/{id}")
    public R<Teacher> byId2(@PathVariable Integer id) {
        log.info(String.valueOf(id));
        Teacher byId = teacherService.getById(id);
        return R.success(byId);
    }
}
